package com.nbst.controller.base;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.nbst.comnutil.*;
import com.nbst.dao.mapper.mes.BillMapper;
import com.nbst.model.api.PrintModel;
import com.nbst.model.base.User;
import com.nbst.service.api.PrintModelService;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: BillController
 * @Description:报表数据接口
 * @Author wl
 * @Date 2021/4/13 15:55
 */
@CrossOrigin
@RestController
@RequestMapping("/bill")
public class BillController {

    @Autowired
    BillMapper billMapper;

    @Autowired
    PrintModelService printModelService;

    /**
     * 客户信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findCustom.action")
    @ResponseBody
    public Object findCustom(String id) {
        List<Map> list = new ArrayList<Map>();
        Map map = new HashMap();
        map.put("id", id);
        list = billMapper.findCustom(map);
        return list;
    }

    @RequestMapping("/saveCustom.action")
    @ResponseBody
    public Object saveCustom(String fName, String fn, String fAddress, String fContact, String fPhone, String fManager, String fEmp) {
        NormalResult result = new NormalResult();
        Map<String, String> map = new HashMap();
        map.put("fName", fName);
        map.put("fn", fn);
        map.put("fAddress", fAddress);
        map.put("fContact", fContact);
        map.put("fPhone", fPhone);
        map.put("fManager", fManager);
        map.put("fEmp", fEmp);
        System.out.println(map);
        billMapper.saveCustom(map);
        result.setCode("0000");
        result.setMessage("成功插入新项目");
        return result;
    }

    @RequestMapping("/savePlanWorktime.action")
    @ResponseBody
    public Object savePlanWorktime(String pname, String ename, String pdate, double worktime) {
        NormalResult result = new NormalResult();
        Map<String, Object> map = new HashMap();
        map.put("pname", pname);
        map.put("ename", ename);
        map.put("pdate", pdate);
        map.put("worktime", worktime);
        billMapper.savePlanWorktime(map);
        result.setCode("0000");
        result.setMessage("成功设定计划工时");
        return result;
    }

    @RequestMapping("getPlanWorktime.action")
    @ResponseBody
    public Object getPlanWorktime(String date) {
        List<String> allDays = WeekUtil.returnAllDays(date);
        List<String> allProjects = new ArrayList<>();
        List<String> allEmp = new ArrayList<>();
        List<Map> ans = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        List<Map> pName = billMapper.findPName(map);
        List<Map> emp = billMapper.findEmp(map);
        for (Map m : pName) {
            if (m == null || m.get("fn") == null) allProjects.add("");
            else allProjects.add((String) m.get("fn"));
        }
        for (Map m : emp) allEmp.add((String) m.get("fName"));
        for (String project : allProjects) {
            Map<String, String> temp = new HashMap<>();
            temp.put("pName", project);
            map.put("pname", project);
            for (String s : allEmp) {
                map.put("ename", s);
                double sum = 0;
                for (String allDay : allDays) {
                    map.put("pdate", allDay);
                    if (billMapper.findPlanWorktime(map) != null) sum += billMapper.findPlanWorktime(map);
                }
                temp.put(s, Double.toString(sum));
            }
            ans.add(temp);
        }
        return ans;
    }

    @RequestMapping("/addEmpForProject.action")
    @ResponseBody
    public Object addEmpForProject(String fn, String fEmp) {
        NormalResult result = new NormalResult();
        Map<String, String> map = new HashMap<>();
        map.put("fn", fn);
        String empInProject = billMapper.getEmpInProject(map);
        if (empInProject == null) map.put("fEmp", fEmp);
        else {
            if (empInProject.contains(fEmp)) {
                result.setCode("1111");
                result.setMessage("已经包含了本次想要添加的员工。");
                return result;
            } else map.put("fEmp", "," + fEmp);
        }
        billMapper.addEmpForProject(map);
        result.setCode("0000");
        result.setMessage("增添成功！");
        return result;
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findEmp.action")
    @ResponseBody
    public Object findEmp(String id) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<Map> list = new ArrayList<Map>();
        Map map = new HashMap();
        if (user != null) {
            String userId = user.getUserCode();
            if (userId != null && !userId.equals("000")) {
                map.put("fNumber", userId);
            }
        }
        list = billMapper.findEmp(map);
        return list;
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findP.action")
    @ResponseBody
    public Object findP(String fdate) {
        List<Map> list = new ArrayList<Map>();
        Map map = new HashMap();
        List<Map> pName = billMapper.findPName(map); // 所有的项目名称
        List<String> allProject = new ArrayList<>();
        List<String> allDays = new ArrayList<>();
        for (Map m : pName) {
            if (m == null || m.get("fn") == null) allProject.add("");
            else allProject.add((String) m.get("fn"));
        }
        String[] split = fdate.split("-");
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        cal = WeekUtil.getFirstDay((Calendar) cal.clone());
        for (int i = 0; i < 7; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append(cal.get(Calendar.YEAR));
            sb.append('-');
            int month = cal.get(Calendar.MONTH) + 1;
            sb.append(month / 10 == 0 ? "0" + month : month);
            sb.append('-');
            int date = cal.get(Calendar.DATE);
            sb.append(date / 10 == 0 ? "0" + date : date);
            allDays.add(sb.toString());
            cal.add(Calendar.DATE, 1);
        }
        for (String day : allDays) {
            map.put("fdate", day);
            Map temp = new HashMap();
            for (String project : allProject) {
                map.put("fproject", project);
                list.add((Map) billMapper.findP(map));
            }
        }
        return list;
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findEZ.action")
    @ResponseBody
    public Object findEZ(String starttime, String endtime, String fName) {
        List<Map> list = new ArrayList<Map>();
        Map map = new HashMap();
        if (!StringUtil.isEmpty(starttime)) {
            map.put("starttime", starttime);
        }
        if (!StringUtil.isEmpty(endtime)) {
            map.put("endtime", endtime);
        }
        if (!StringUtil.isEmpty(fName)) {
            map.put("fName", fName);
        }
        list = billMapper.findEZ(map);
        return list;
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findPZ.action")
    @ResponseBody
    public Object findPZ(String day) {
        Map map = new HashMap();
        List<String> allDays = WeekUtil.returnAllDays(day);
        List<String> allPros = new ArrayList<>();
        List<Map> p = billMapper.findCustom(map);
        List<Map> list=new ArrayList<>();
        for (Map m : p) {
            allPros.add((String) m.get("fn"));
        }
        for (String pro : allPros) {
            Map temp=new HashMap();
            temp.put("pro",pro);
            map.put("pro",pro);
            double hplan = planHourInWeek(day, pro);
            double sum=0;
            for(int i=0;i<7;i++){
                map.put("date",allDays.get(i));
                Double pz = billMapper.findPZ(map)==null?0.0:billMapper.findPZ(map);
                temp.put("day"+i,String.valueOf(pz));
                sum+=pz;
            }
            temp.put("sum",String.valueOf(sum));
            temp.put("hplan",String.valueOf(hplan));
            temp.put("hdiff",String.valueOf(sum-hplan));
            temp.put("dsum",String.valueOf(sum/7.5));
            temp.put("dplan",String.valueOf(hplan/7.5));
            temp.put("ddiff",String.valueOf((sum-hplan)/7.5));
            list.add(temp);
        }
        return list;
    }

    @RequestMapping("/findEPZ.action")
    @ResponseBody
    public Object findEPZ(String pro,String day){
        Map map=new HashMap();
        List<Map> emp = billMapper.findEmp(map);
        List<String> allDays = WeekUtil.returnAllDays(day);
        List<String> allEmps=new ArrayList<>();
        List<Map> ans=new ArrayList<>();
        for (Map m : emp) {
            allEmps.add((String) m.get("fName"));
        }
        map.put("pro",pro);
        for (String e : allEmps) {
            Map temp=new HashMap();
            map.put("ename",e);
            temp.put("name",e);
            double sum=0;
            for(int i=0;i<7;i++){
                map.put("date",allDays.get(i));
                double increasement=billMapper.findE(map)==null?0.0:billMapper.findE(map);
                temp.put("day"+i,String.valueOf(increasement));
                sum+=increasement;
            }
            temp.put("hsum",String.valueOf(sum));
            double hplan = planHourInWeekOneEmp(day, e, pro);
            temp.put("hplan",String.valueOf(hplan));
            temp.put("hdiff",String.valueOf(sum-hplan));
            temp.put("dsum",String.valueOf(sum/7.5));
            temp.put("dplan",String.valueOf(hplan/7.5));
            temp.put("ddiff",String.valueOf((sum-hplan)/7.5));
            ans.add(temp);
        }
        return ans;
    }


    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findprocedureSelectP.action")
    @ResponseBody
    public Object findprocedureSelectP(String id) {
        List<Map> list = new ArrayList<Map>();
        Map map = new HashMap();
        map.put("id", id);
        list = billMapper.findprocedureSelectP(map);
        return list;
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findprocedureSelectE.action")
    @ResponseBody
    public Object findprocedureSelectE(String id) {
        List<Map> list = new ArrayList<Map>();
        Map map = new HashMap();
        map.put("id", id);
        list = billMapper.findprocedureSelectE(map);
        return list;
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/saveEP.action")
    @ResponseBody
    public Object saveEP(String eName, String eid, String pName, String pid, String fdate, String eqty) {
        NormalResult result = new NormalResult();
        Map map = new HashMap();
        map.put("eName", eName);
        map.put("eid", eid);
        map.put("pName", pName);
        map.put("pid", pid);
        map.put("fdate", fdate);
        map.put("eqty", eqty);
        billMapper.saveEP(map);
        result.setCode("0000");
        result.setMessage("操作成功");
        return result;
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/removeEP.action")
    @ResponseBody
    public Object removeEP(String xh) {
        NormalResult result = new NormalResult();
        Map map = new HashMap();
        map.put("xh", xh);
        billMapper.removeEP(map);
        result.setCode("0000");
        result.setMessage("操作成功");
        return result;
    }


    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findEP.action")
    @ResponseBody
    public Object findEP(Model model, String id, HttpSession session) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();

//        List<String> pnamelist = billMapper.findPName();
//        System.out.println(pnamelist);

        List<Map> list = new ArrayList<>(); // list用于储存返回的结果集合
        Map map = new HashMap(); // 作为查询的参数传入
        List<Map> pName = billMapper.findPName(map); // pName用于存储从数据库中得到的所有项目名称。
        List<String> allProject = new ArrayList<>();
        List<String> allDays = new ArrayList<>();
        System.out.println(pName);
        for (Map m : pName) {
            if (m == null || m.get("fn") == null) allProject.add("");
            else allProject.add((String) m.get("fn"));
        }
        //Calendar cal = (Calendar) model.getAttribute("cal");
        Calendar cal = (Calendar) session.getAttribute("cal");
        System.out.println(cal);
        cal = WeekUtil.getFirstDay((Calendar) cal.clone());
        for (int i = 0; i < 7; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append(cal.get(Calendar.YEAR));
            sb.append('-');
            int month = cal.get(Calendar.MONTH) + 1;
            sb.append(month / 10 == 0 ? "0" + month : month);
            sb.append('-');
            int date = cal.get(Calendar.DATE);
            sb.append(date / 10 == 0 ? "0" + date : date);
            allDays.add(sb.toString());
            cal.add(Calendar.DATE, 1);
        }
        System.out.println("all Projects: " + pName);
        String username = (String) session.getAttribute("eName");
        if (username != null) { // 在有参数的情况下
            Map<String, String> tempmap = new HashMap<>();
            tempmap.put("username", username);
            String usercode = billMapper.findUserCodeByName(tempmap);
            map.put("fNumber", usercode);
        } else if (user != null) {
            String userId = user.getUserCode();
            if (userId != null) {
                if (userId.equals("000")) { // 如果是管理员账户
                    map.put("fNumber", "005"); // 默认展示005
                } else map.put("fNumber", userId);
                //System.out.println(userId);
            }
        }

        for (String s : allProject) {
            Map<String, String> ans = new HashMap<>(); // 结果map 用来构建回传的list 每一个项目有一个ans
            int sum = 0;
            map.put("fProject", s);
            ans.put("fn", s);
            for (int i = 1; i <= 7; i++) {
                map.put("fDate", allDays.get(i - 1));
                System.out.println(map);
                Double worktime = billMapper.findEPByDate(map);
                if (worktime == null) worktime = 0.0;
                System.out.println(worktime);
                ans.put("day" + i, worktime == 0.0 ? "-" : Double.toString(worktime));
                sum += worktime;
            }
            ans.put("sum", Double.toString(sum));
            list.add(ans);
        }
        //list = billMapper.findEP(map);
        //System.out.println(list);
        return list;
    }

    @RequestMapping(value = "/changeCalSession.action")
    public void changeCalSession(HttpSession session, String eName, String cal) {
        String[] split = cal.split("-");
        Calendar newcal = Calendar.getInstance();
        newcal.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        //System.out.println("newcal!:   " + newcal);
        session.setAttribute("cal", newcal);
        session.setAttribute("eName", eName);
        System.out.println("new session: " + session.getAttribute("cal"));
        System.out.println("new session: " + session.getAttribute("eName"));
    }

    @RequestMapping(value = "/refreshModel.action")
    public String refreshModel(HttpSession session, Model model) {
        Calendar cal = (Calendar) session.getAttribute("cal");
        Map<String, Object> dateinfo = new HashMap<>();
        dateinfo.put("year", WeekUtil.yearNoCount((Calendar) cal.clone()));
        dateinfo.put("month", WeekUtil.monthNoCount((Calendar) cal.clone()));
        dateinfo.put("week", WeekUtil.weekNoCount((Calendar) cal.clone()));
        dateinfo.put("name", model.getAttribute("name"));
        cal = WeekUtil.getFirstDay((Calendar) cal.clone());
        for (int i = 0; i < 7; i++) {
            dateinfo.put("day" + i, cal.get(Calendar.YEAR) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.DATE));
            cal.add(Calendar.DATE, 1);
        }
        model.addAttribute("dateinfo", dateinfo);
        return "<h3><span id=\"year\">" + dateinfo.get("year") + "</span>年<span id=\"month\">" + dateinfo.get("month") + "</span>月第<span id=\"week\">" + dateinfo.get("week") + "</span>周项目工时</h3>\n" +
                "<table class=\"table\">\n" +
                "<tr style=\"text-align: center\">\n" +
                "<td>" + dateinfo.get("name") + "</td>\n" +
                "<td><span id=\"day0\">" + dateinfo.get("day0") + "</span><br>周一</td>\n" +
                "<td><span id=\"day1\">" + dateinfo.get("day1") + "</span><br>周二</td>\n" +
                "<td><span id=\"day2\">" + dateinfo.get("day2") + "</span><br>周三</td>\n" +
                "<td><span id=\"day3\">" + dateinfo.get("day3") + "</span><br>周四</td>\n" +
                "<td><span id=\"day4\">" + dateinfo.get("day4") + "</span><br>周五</td>\n" +
                "<td><span id=\"day5\">" + dateinfo.get("day5") + "</span><br>周六</td>\n" +
                "<td style=\"color: red\"><span id=\"day6\">" + dateinfo.get("day6") + "</span><br>周日</td>\n" +
                "<td>小结</td>\n" +
                "</tr>\n" +
                "</table>";
    }

    /**
     * 员工信息
     *
     * @return Map
     * @author wl
     * @date 2021/1/28 0028 11:34
     */
    @RequestMapping("/findE.action")
    @ResponseBody
    public Object findE(String day) {
        Map map = new HashMap();
        List<Map> list = new ArrayList<Map>();
        List<String> allDays = WeekUtil.returnAllDays(day);
        List<String> allEmps = new ArrayList<>();
        List<Map> emps = billMapper.findEmp(map);
        for (Map emp : emps) {
            allEmps.add((String) emp.get("fName"));
        }
        for (String emp : allEmps) {
            Map<String, String> temp = new HashMap<>();
            temp.put("name", emp);
            map.put("ename", emp);
            double sum = 0, strdh = 37.5, strdd = 6.2;
            for (int i = 0; i < 7; i++) {
                map.put("date", allDays.get(i));
                Double e = billMapper.findE(map) == null ? 0.0 : billMapper.findE(map);
                sum += e;
                temp.put("date" + i, String.valueOf(e));
            }
            temp.put("hsum", String.valueOf(sum));
            temp.put("hdiff", String.valueOf(sum - strdh));
            temp.put("hstrd", String.valueOf(strdh));
            temp.put("dsum", String.valueOf(sum / 7.5));
            temp.put("ddiff", String.valueOf((sum - strdh) / 7.5));
            temp.put("dstrd", String.valueOf(strdd));
            list.add(temp);
        }
        return list;
    }


    /**
     * 打印参数传入
     *
     * @param newStr  参数
     * @param preview 是否预览，0不预览 1预览
     * @return java.lang.Object
     * @author King
     * @date 2021/4/14 0014 22:46
     */
    @RequestMapping("/getPrintGRF.action")
    @ResponseBody
    public NormalResult getPrintGRF(String code, String newStr, String preview, HttpServletRequest request) throws IOException {
        String clientip = HttpUtil.getIpAddress(request);
        NormalResult nr = new NormalResult();
        Map queryWrapper = new HashMap<>();
        queryWrapper.put("code", code);
        PrintModel printModel = printModelService.findPrintModel(queryWrapper);
        if (printModel != null) {
            System.out.println(clientip);
            // nr = FileUtils.toPrint(printModel,newStr,preview,clientip);
            String fileUrl = FileUtils.replaceFile(printModel, newStr);
            nr.setCode(Constants.DefaultResultEnums.SYSTEM_NORMAL.getCode());
            nr.setMessage(Constants.DefaultResultEnums.SYSTEM_NORMAL.getName());
            nr.setDesc(printModel.getUrl() + fileUrl.replace("\\", "/"));
            nr.setType(fileUrl.substring(fileUrl.indexOf("\\") + 1));
        }
        return nr;
    }

    private double planHourInWeek(String date,String pro){
        double sum=0.0;
        List<String> allDays = WeekUtil.returnAllDays(date);
        Map map=new HashMap();
        map.put("pname",pro);
        for (String s : allDays) {
            map.put("pdate",s);
            sum+= billMapper.findPlanWorktime(map)==null?0.0:billMapper.findPlanWorktime(map);
        }
        return sum;
    }

    private double planHourInWeekOneEmp(String date,String pro,String Emp){
        Map map=new HashMap();
        List<String> allDays = WeekUtil.returnAllDays(date);
        map.put("pname",pro);
        map.put("ename",Emp);
        double sum=0;
        for (String day : allDays) {
            map.put("pdate",day);
            sum+=billMapper.findPlanWorktime(map)==null?0.0:billMapper.findPlanWorktime(map);
        }
        return sum;
    }

}
